package com.tfswx.jkgl.designer.aop;

import cn.hutool.core.bean.BeanUtil;
import com.tfswx.jkgl.core.bean.JkglRuntimeData;
import com.tfswx.jkgl.designer.datasource.DynamicDataSourceContextHolder;
import com.tfswx.jkgl.designer.service.ExportService;
import com.tfswx.jkgl.designer.service.JkglService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author ricky
 * @date 2021/12/14
 */
@Slf4j
@Aspect
@Component
public class ApiAcpect {
    @Resource
    private JkglService jkglService;
    @Resource
    private ExportService exportService;
    @Resource
    private JkglRuntimeData jkglRuntimeData;

    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(public * com.tfswx.jkgl.core.api.ApiController.*(..))")
    public void api() {
    }

    @Before("api()")
    public void doBefore(JoinPoint joinPoint) {
        log.info("开始aop");
        Object[] args = joinPoint.getArgs();
        String xmbm;
        if (args.length == 2) {
            String jkbm = String.valueOf(args[0]);
            xmbm = jkglService.getXmbmByJkbm(jkbm);
        } else if (args.length == 3) {
            String mkbs = String.valueOf(args[0]);
            String jkmc = String.valueOf(args[1]);
            xmbm = jkglService.getXmbmByMkbsAndJkmc(mkbs, jkmc);
        } else {
            throw new RuntimeException("接口调用缺少参数，请检查");
        }
        JkglRuntimeData temp = exportService.getJkglRuntimeData(xmbm);

        BeanUtil.copyProperties(temp, jkglRuntimeData);

        DynamicDataSourceContextHolder.setDataSourceType(xmbm);
    }

    private HttpServletResponse getResponse() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            return ((ServletRequestAttributes) requestAttributes).getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    @Around("api()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object o;
        try {
            o = joinPoint.proceed();
        } finally {
            HttpServletResponse response = getResponse();
            if (response != null) {
                response.setHeader("time", String.valueOf(System.currentTimeMillis() - startTime));
            }
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
        // Map<String, Object> res = new HashMap<>();
        // res.put("data", o);
        // res.put("code", 200);
        // res.put("message", "操作成功");
        // res.put("success", true);
        return o;
    }


    @Around("api()")
    public Object doAfter(ProceedingJoinPoint joinPoint) throws Throwable {
        Object o = joinPoint.proceed();
        if (o == null) {
            HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("code", 0);
            objectObjectHashMap.put("message", "操作成功");
            objectObjectHashMap.put("success", true);
            objectObjectHashMap.put("data", null);
            return objectObjectHashMap;
        }
        return o;
    }
}
